package com.youlai.netty.service.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.http.HttpClient;

/**
 * @author zc
 * @date 2023-02-04 22:18
 */
@Slf4j
public class HTTPHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)  {
        log.info("HTTPServer收到：{}",msg.toString());
                if(msg instanceof HttpRequest) {
                    //1.打印浏览器的请求地址
                  log.info("客户端地址：" + ctx.channel().remoteAddress());
                    //2.给浏览器发送的信息，封装成ByteBuf
                    ByteBuf content = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
                    //3.构造一个http的相应，即 httpresponse
                    FullHttpResponse response = new DefaultFullHttpResponse(
                            HttpVersion.HTTP_1_1,
                            HttpResponseStatus.OK,
                            content);
                    //4.设置响应头信息-响应格式
                    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                    //5.设置响应头信息-响应数据长度
                    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
                    //6.将构建好 response返回
                    ctx.writeAndFlush(response);
                }

    }
}
